package com.gonsin.gmessage.logic.proxy;

import com.gonsin.gmessage.annotations.GMessageEnvironment;
import com.gonsin.gmessage.logic.model.GMessageModel;
import com.gonsin.gmessage.logic.mqtt.MqttClientManager;
import com.gonsin.gmessage.logic.websocket.WebSocketSessionContainer;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.mqttv5.client.IMqttToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@Slf4j
public class MessageSender {

//    @Autowired private MqttGateWay mqttGateWay;
    @Autowired private MqttClientManager mqttGateWay;
    @Autowired private WebSocketSessionContainer sessionContainer;


    /**
     * 发送消息
     */
    public IMqttToken send(int qos, boolean share, GMessageModel message){
        if(GMessageEnvironment.LOG){
            if(StringUtils.isEmpty(message.getZoom())){
                log.info("向全局发送消息：{}", new Gson().toJson(message));
            } else {
                log.info("向域【{}】发送消息：{}", message.getZoom(), new Gson().toJson(message));
            }
        }


        // 发送MQTT
        String topicName = ("venus/") + message.getCmd().getFirstcmd() + "/" + message.getCmd().getSubcmd() + (message.getZoom() == null ? "" : ("/" + message.getZoom()));
        if(share){
            topicName = "$SHARE/" + topicName;
        }
        String payload = new Gson().toJson(message);
        return mqttGateWay.publish(topicName, qos, payload);

        // 自 20240824 开始，不再 发送 Websocket 的 GMessage
        // 发送Websocket
//        sessionContainer.sendCmd(message.getZoom(), message);

        // TODO 其他协议待补充

    }

}
